package com.mathassistant.server;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mathassistant.client.service.FinalTestService;
import com.mathassistant.server.domain.FinalTest;
import com.mathassistant.server.domain.Topic;
import com.mathassistant.shared.FinalTestDTO;
import com.mathassistant.shared.TopicDTO;

@SuppressWarnings("serial")
public class FinalTestServiceImpl extends RemoteServiceServlet implements FinalTestService{

	@Override
	public void createFinalTest(FinalTestDTO exam, TopicDTO topicParent) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Topic itp = pm.getObjectById(Topic.class, topicParent.getId());
			FinalTest ex = new FinalTest(exam);
			pm.makePersistent(ex);
			itp.setExam(ex);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}

	@Override
	public void updateFinalTest(FinalTestDTO exam) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			FinalTest ex = pm.getObjectById(FinalTest.class, exam.getId());
			ex.updateFromDTO(exam);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}

	@Override
	public void deleteFinalTest(FinalTestDTO exam) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			FinalTest ex = pm.getObjectById(FinalTest.class, exam.getId());
			if(ex != null){
				pm.deletePersistent(pm.getObjectById(FinalTest.class, exam.getId()));
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}

	@Override
	public FinalTestDTO getFinalTest(TopicDTO topicParent) {
		// TODO Auto-generated method stub
		FinalTestDTO result = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Topic itp = pm.getObjectById(Topic.class, topicParent.getId());
			if(itp != null){
				FinalTest kq = itp.getExam();
				if(kq != null){
					result = new FinalTestDTO(kq.toDTO());
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return result;
	}

}
